package com.tianye.salon.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.tianye.salon.dao.AdminRoleMapper;
import com.tianye.salon.exception.MyException;
import com.tianye.salon.model.AdminModule;
import com.tianye.salon.model.AdminRole;
import com.tianye.salon.service.AdminRoleService;




@Service("adminRoleService")
public class AdminRoleServiceImpl extends BaseServiceImpl<AdminRole, AdminRoleMapper> implements AdminRoleService{
	
	@Autowired
	private AdminRoleMapper adminRoleMapper;

	@Override
	public AdminRoleMapper getMapper() throws Exception {
		return adminRoleMapper;
	}
	
	public int insertRoleAndModules(AdminRole role) throws MyException{
		try {
			adminRoleMapper.insert(role);
		} catch (DuplicateKeyException e) {
			throw new MyException("名称【"+role.getName()+"】重复，请检查！");
		}
		
		//System.out.println("role is:"+role);
		List<AdminModule> modules = role.getModules();
		for(AdminModule module: modules){
			adminRoleMapper.insertrolemodule(role, module);
		}
		return 0;
	}
	
	public int deleteRoleModulesByRoleid(int rid) {
		return adminRoleMapper.deleteRoleModulesByRoleid(rid);
	}
	
	public int updateRoleModules(AdminRole role) throws MyException{
		try {
			adminRoleMapper.updateRole(role);
		} catch (DuplicateKeyException e) {
			throw new MyException("名称【"+role.getName()+"】重复，请检查！");
		}
		
		List<AdminModule> modules = role.getModules();
		for(AdminModule module: modules){
			adminRoleMapper.insertrolemodule(role, module);
		}
		return 0;
	}
	
	public int deleteRoleModules(int rid) {
		adminRoleMapper.deleteRoleModulesByRoleid(rid);
		adminRoleMapper.deleteByPrimaryKey(rid);
		
		return 0;
	}
	
	public AdminRole selectRoleModuleByPrimaryKey(int id) {
		return adminRoleMapper.selectRoleModuleByPrimaryKey(id);
	}
}
